﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Volo.Abp.BackgroundWorkers;
using Volo.Abp.Threading;
using YaAppoint.Appointments.CheckIn;
using YaAppoint.CustomSettings;

namespace YaAppoint.BackgroundWorkers
{
    /// <summary>
    /// 自动签到(定时任务)
    /// </summary>
    public class AutoCheckInWorker : AsyncPeriodicBackgroundWorkerBase
    {
        private readonly ICustomSettingAppService _customSettingAppService;

        public AutoCheckInWorker(AbpAsyncTimer timer,
                                 ICustomSettingAppService customSettingAppService,
                                 IServiceScopeFactory serviceScopeFactory)
            :base(timer,serviceScopeFactory)
        {
            Timer.Period = 600000; // 十分钟
            _customSettingAppService = customSettingAppService;
        }

        //  执行任务内容
        protected override async Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext)
        {
            var globalSetting = await _customSettingAppService.GetGlobalSetting();
            if (globalSetting.CheckInMode == CheckInMode.Auto)
            {
                Logger.LogInformation("开始自动签到");
                // 从serviceProvider接口解析依赖注入
                ICheckInAppService checkInService = workerContext.ServiceProvider.GetRequiredService<ICheckInAppService>();
                await checkInService.AutoCheckIn();

                Logger.LogInformation("自动签到结束，未成功的签到已记录");
            }
        }
    }
}
